#include "datetimedelegate.h"

#include "cashplusplus.h"

DateTimeDelegate::DateTimeDelegate(QObject* parent)
	: QStyledItemDelegate(parent)
{
}

QWidget* DateTimeDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem&, const QModelIndex&) const
{
	return new QDateTimeEdit(parent);
}

void DateTimeDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
	uint value = index.model()->data(index, Qt::EditRole).toUInt();

	QDateTimeEdit *dte = static_cast<QDateTimeEdit*>(editor);
	dte->setDateTime(QDateTime::fromTime_t(value));
}

void DateTimeDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
	QDateTimeEdit *dte = static_cast<QDateTimeEdit*>(editor);
	dte->interpretText();

	QDateTime val = dte->dateTime();
	model->setData(index, val.toTime_t(), Qt::EditRole);
}

void DateTimeDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex&) const
{
	editor->setGeometry(option.rect);
}

QString DateTimeDelegate::displayText(const QVariant &value, const QLocale& locale) const
{
	QDateTime time = QDateTime::fromTime_t(QStyledItemDelegate::displayText(value, locale).toUInt());
	return time.toString(CashPlusPlus::DATETIME_FORMAT);
}

